package com.vinjogames.network;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

import com.vinjogames.util.Logger;

public class Client{
	private static String mServerIP;
	private int mPort;
	private Socket mSocket;
	private PrintWriter out;
	private static final int TIMEOUT = 10;

	public boolean mConnected = false;

	public Client() {
		Logger.log("[Client] Constructor");
	}

	public boolean Connect(String serverIP, int port){
		//Regex for ip
		//\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
		mServerIP = serverIP;
		mPort = port;
		
		Logger.log("[Client] Connecting to: " + mServerIP);
		if (!mConnected) {
			if (!mServerIP.equals("")) {
				Thread cThread = new Thread(new ClientThread());
				cThread.start();
			}
		}
		
		for(int i = 0; i < TIMEOUT; i++){
			if(!mConnected){
				try {
					Logger.log("[Client] wait.. " + (TIMEOUT - i));
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					Logger.log("[Client] Exception on wait:" + e.getMessage());
				}
			}
			else{
				
				break;
			}
		}
		return mConnected;
	}

	public void Disconnect(){
		if (mConnected) {
			try {
				mSocket.close();
				mConnected = false;
				out = null;
				Logger.log("[Client] Closed.");
			} catch (Exception e) {
				Logger.log("[Client] Exception: " + e.getMessage());
			}
		}
	}

	public class ClientThread implements Runnable {
		public void run() {
			try {
				Logger.log("[Client] Connecting...");
				InetAddress serverAddr = InetAddress.getByName(mServerIP);
				mSocket = new Socket(serverAddr, mPort);
				mConnected = true;
			} catch (Exception e) {
				Logger.log("[Client] Exception: ", e.getMessage());
				mConnected = false;
			}
		}
	}
	
	public void SendMessage(String msg){
		Logger.log("[Client]  Sending msg.");
		if (mConnected) {
			try {
				Logger.log("[Client]  Sending command.");
				if(out == null){
					out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true);
				}
				// where you issue the commands
				out.println(msg);
				Logger.log("[Client] Sent.");
			} catch (Exception e) {
				Logger.log("[Client] Exception: " + e.getMessage());
			}
		}
	}
	
	public String getServerIP() { return mServerIP; }
}